/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
// AxiosProgressEvent
import qs from 'qs'
import { showToast } from 'vant'

import { useUserStore } from '@/store/modules/user'

axios.interceptors.request.use(async(config:AxiosRequestConfig | any) => {
  const UserStore = useUserStore()

  const token = UserStore.token

  // 自定义请求头
  if (config && config?.headers && !config.headers.noToken) {
    config.headers.Authorization = token
  }

  //   if (token) { config.headers['token'] = token }
  return config
}, (error:AxiosError) => {
  return Promise.reject(error)
})
axios.interceptors.response.use((response:AxiosResponse) => {
  // 直接返回res，当然你也可以只返回res.data
  // 系统如果有自定义code也可以在这里处理
  const UserStore = useUserStore()
  if (response.status && response.status === 200) {
    if (response.data.code === 401) {
      UserStore.logout()
    }
    return response
  }
  const err = new Error(response.data.msg)
  // err.data = res
  // err.response = res

  throw err
}, (error:AxiosError) => {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = '请求错误(400)'
        break
      case 401:
        error.message = '未授权，请重新登录(401)'
        break
      case 403:
        error.message = '拒绝访问(403)'
        break
      case 404:
        error.message = '请求出错(404)'
        break
      case 408:
        error.message = '请求超时(408)'
        break
      case 500:
        error.message = '服务器错误(500)'
        break
      case 501:
        error.message = '服务未实现(501)'
        break
      case 502:
        error.message = '网络错误(502)'
        break
      case 503:
        error.message = '服务不可用(503)'
        break
      case 504:
        error.message = '网络超时(504)'
        break
      case 505:
        error.message = 'HTTP版本不受支持(505)'
        break
      default:
        error.message = `连接出错(${error.response.status})!`
    }
  } else {
    error.message = '连接服务器失败!'
  }

  showToast(error.message)
  return Promise.reject(error)
})

class HttpRequest {
  constructor() {
    axios.defaults.baseURL = import.meta.env.VITE_NODE_ENV_API
    axios.defaults.timeout = 6300000
    axios.defaults.headers.post['Content-Type'] =
      'application/x-www-form-urlencoded'
  }

  /**
   * GET 请求
   */
  async get(url:string, resData = {}) {
    try {
      const { data } = await axios.get(url, {
        params: resData
      })
      return data
    } catch (error) {
      return error
    }
  }

  /**
   * GET 请求
   */
  async transferFormatGet(url:string, resData = {}) {
    try {
      const { data } = await axios({
        headers: {
          'Content-Type': 'text/pdf;charset=x-user-defined'
        },
        method: 'GET',
        url: url,
        params: resData,
        responseType: 'blob'
      })
      return data
    } catch (error) {
      return error
    }
  }

  /**
   * POST 请求
   * Content-Type: application/x-www-form-urlencoded
   * formDate
   */
  async post(url:string, resData = {}) {
    try {
      const { data } = await axios.post(url, qs.stringify(resData))
      return data
    } catch (error) {
      return error
    }
  }

  /**
   * POST 请求
   * Content-Type: application/json
   * Json
   */
  async postJSON(url:string, resData = {}) {
    try {
      const { data } = await axios({
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: url,
        data: resData
      })
      return data
    } catch (error) {
      return error
    }
  }

  /**
   * POST 请求
   * 无token请求
   * Json
   */
  async noTokenPost(url:string, resData = {}) {
    try {
      const { data } = await axios({
        headers: {
          'noToken': true,
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: url,
        data: resData
      })
      return data
    } catch (error) {
      return error
    }
  }

  /**
   * POST 请求
   * Content-Type: multipart/form-data
   * form-data
   * 文件上传
   */
  async uploadFile(url:string, resData = {}, progressFun?: any) {
    // url, resData,
    try {
      const { data } = await axios({
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        method: 'post',
        url: url,
        data: resData,
        onUploadProgress: progressFun
      })
      return data
    } catch (error) {
      return error
    }
  }
  async uploadFile2(url:string, resData = {}) {
    // url, resData,
    try {
      const { data } = await axios({
        data: resData,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        method: 'post',
        url: url
      })
      return data
    } catch (error) {
      return error
    }
  }
}

export default new HttpRequest()

